<template>
    <view class="u-input u-border item" @tap="show = true">
        <view class="l-select-label">
            {{ label }}
        </view>
        <view class="flex-1 ml-2">
            {{ showList[currentIndex] && showList[currentIndex][keyName] }}
            <text class="text-gray-400" v-if="modelValue === undefined || modelValue === ''">{{ placeholder }}</text>
        </view>
        <u-icon name="arrow-down"></u-icon>
    </view>

    <u-picker closeOnClickOverlay :defaultIndex="[defaultIndex]" :show="show" :keyName="keyName" @cancel="show = false"
        @close="show = false" :columns="[showList]" @confirm="confirm"></u-picker>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
let props = withDefaults(defineProps<{
    label?: string,
    modelValue?: number | string,
    placeholder?: string,
    list: Array<{ [key: string]: string, value: any }>,
    keyName: string
}>(), {
    placeholder: '请选择',
    list: () => [],
    keyName: 'label'
})

let emit = defineEmits(['update:modelValue'])
let show = ref(false);
let showList = computed(() => {
    if (typeof props.list[0] == 'string' || typeof props.list[0] == 'number') {
        return props.list.map((item: any, idx: number) => ({ [props.keyName]: item, value: item }))
    } else {
        return props.list
    }
})

function confirm(item: any) {
    show.value = false;
    let selectItem = showList.value[item.indexs[0]]
    if (selectItem?.value !== undefined) emit('update:modelValue', selectItem.value);
}
let currentIndex = computed(() => showList.value.findIndex(item => props.modelValue == item.value));
let defaultIndex = computed(() => Math.max(0, currentIndex.value));

</script>
<style scoped lang="scss">
.item {
    @apply rounded h-[24px] py-[6px] px-[9px] flex items-center box-content;
}
</style>
<style lang="scss">
l-select {
    @apply block;
}
</style>